<template>
  <div class="product-management">
    <!-- 装饰性背景元素 -->
    <div class="background-decorations">
      <div class="bg-circle bg-circle-1"></div>
      <div class="bg-circle bg-circle-2"></div>
      <div class="bg-circle bg-circle-3"></div>
    </div>
    
    <div class="management-content">
      <!-- 搜索区域 -->
      <div class="search-container">
        <el-input
          v-model="searchQuery"
          placeholder="请输入产品名称搜索"
          class="search-input"
          @input="debounceSearch"
        >
          <template #suffix>
            <el-icon @click="handleSearch"><Search /></el-icon>
          </template>
        </el-input>
        
        <!-- 新增：产品类型下拉选择器 -->
        <el-select 
          v-model="selectedProductTypeId" 
          placeholder="请选择产品类型"
          class="search-select"
          @change="handleSearch"
        >
          <el-option label="全部" value="" />
          <el-option 
            v-for="type in productTypes" 
            :key="type.id" 
            :label="type.cnName" 
            :value="type.id" 
          />
        </el-select>
        
        <!-- 将新增产品按钮移到搜索区域 -->
        <el-button type="primary" class="primary-button" @click="showAddDialog">新增产品</el-button>
      </div>
      
      <!-- 表格区域 -->
      <el-table :data="products" fit>
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="code" label="商品条码" width="150" align="center" />
        <el-table-column prop="name" label="产品名称" width="180" align="center" />
        <el-table-column prop="productTypeName" label="商品类型名称" width="150" align="center" />
        <el-table-column prop="accessMethod" label="接入方式" width="100" align="center" />
        <el-table-column prop="authMethod" label="认证方式" width="170" align="center" />
        <el-table-column prop="status" label="状态" width="150" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status.includes('启用') ? 'success' : 'danger'" size="small">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="authPassword" label="操作认证密码" width="150" align="center">
          <template #default="scope">
            <div @click="togglePasswordVisibility(scope.row.id)" style="cursor: pointer;">
              {{ showPasswords[scope.row.id] ? scope.row.authPassword : '***' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right" align="center" :show-overflow-tooltip="false">
          <template #default="scope">
            <el-button type="primary" size="small" @click="toggleStatus(scope.row)">{{ scope.row.status.includes('启用') ? '禁用' : '启用' }}</el-button>
            <el-button type="primary" size="small" @click="editProduct(scope.row)">编辑</el-button>
            <el-button type="info" size="small" @click="viewProductProperties(scope.row.id)">查看物属性</el-button>
            <el-button type="danger" size="small" @click="deleteProduct(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑产品对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="1200px" draggable>
      <el-form ref="formRef" :model="formData" label-width="120px">
        <el-form-item label="产品条码" prop="code" :rules="[{ required: true, message: '请输入产品条码', trigger: 'blur' }]">
          <el-input v-model="formData.code" placeholder="请输入产品条码" />
        </el-form-item>
        <el-form-item label="产品名称" prop="name" :rules="[{ required: true, message: '请输入产品名称', trigger: 'blur' }]">
          <el-input v-model="formData.name" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="产品类型" prop="productTypeId" :rules="[{ required: true, message: '请选择产品类型', trigger: 'change' }]">
          <el-select v-model="formData.productTypeId" placeholder="请选择产品类型">
            <el-option v-for="type in productTypes" :key="type.id" :label="type.cnName" :value="type.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="认证密码" prop="authPassword" :rules="[{ required: true, message: '请输入认证密码', trigger: 'blur' }]">
          <el-input v-model="formData.authPassword" placeholder="请输入认证密码" type="password" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="formData.comment" type="textarea" placeholder="请输入产品描述" />
        </el-form-item>
        <el-form-item label="接入方式" prop="accessMethod" :rules="[{ required: true, message: '请选择接入方式', trigger: 'change' }]">
          <el-select v-model="formData.accessMethod" placeholder="请选择接入方式">
            <el-option label="MQTT" value="MQTT" />
          </el-select>
        </el-form-item>
        <el-form-item label="认证方式" prop="authMethod" :rules="[{ required: true, message: '请选择认证方式', trigger: 'change' }]">
          <el-select v-model="formData.authMethod" placeholder="请选择认证方式">
            <el-option label="设备密码" value="DEVICEPASSWORD" />
            <el-option label="证书认证" value="DEVICECERTIFICATE" />
          </el-select>
        </el-form-item>
        
        <!-- 物模型配置 -->
        <el-form-item label="物模型属性">
          <el-button type="primary" size="small" @click="addProperty" style="margin-bottom: 10px;">新增属性</el-button>
          <!-- 使用更简洁的布局，移除border，确保所有元素完全对齐 -->
          <div style="overflow-x: auto;">
            <table style="width: 100%; border-collapse: collapse; table-layout: fixed;">
              <!-- 表头 -->
              <thead>
                <tr style="background-color: #f5f7fa; height: 36px;">
                  <th style="width: 80px; text-align: center; padding: 8px; border: 1px solid #ebeef5;">属性</th>
                  <th style="width: 80px; text-align: center; padding: 8px; border: 1px solid #ebeef5;">属性名</th>
                  <th style="width: 60px; text-align: center; padding: 8px; border: 1px solid #ebeef5;">数据类型</th>
                  <th style="width: 80px; text-align: center; padding: 8px; border: 1px solid #ebeef5;">数据范围</th>
                  <th style="width: 80px; text-align: center; padding: 8px; border: 1px solid #ebeef5;">精度</th>
                  <th style="width: 60px; text-align: center; padding: 8px; border: 1px solid #ebeef5;">读取方式</th>
                   <th style="width: 80px; text-align: center; padding: 8px; border: 1px solid #ebeef5;">属性值</th>
                    <th style="width: 80px; text-align: center; padding: 8px; border: 1px solid #ebeef5;">描述</th>
                  <th style="width: 80px; text-align: center; padding: 8px; border: 1px solid #ebeef5;">操作</th>
                </tr>
              </thead>
              <!-- 数据行 -->
              <tbody>
                <tr v-for="(property, index) in formData.properties" :key="index" style="height: 40px;">
                  <td style="width: 100px; padding: 4px; border: 1px solid #ebeef5;">
                    <el-input v-model="property.property" placeholder="请输入属性" size="small" style="width: 100%;" />
                  </td>
                  <td style="width: 100px; padding: 4px; border: 1px solid #ebeef5;">
                    <el-input v-model="property.propertyName" placeholder="请输入属性名" size="small" style="width: 100%;" />
                  </td>
                  <td style="width: 100px; padding: 4px; border: 1px solid #ebeef5;">
                      <el-select v-model="property.dataType" placeholder="数据类型" size="small" style="width: 100%;">
                        <el-option label="整数" value="integer" />
                        <el-option label="浮点数" value="float" />
                        <el-option label="双精度" value="double" />
                        <el-option label="布尔值" value="boolean" />
                        <el-option label="字符串" value="string" />
                      </el-select>
                    </td>
                  <td style="width: 120px; padding: 4px; border: 1px solid #ebeef5;">
                    <el-input v-model="property.dataRange" placeholder="数据范围如:0-100"  size="small" style="width: 100%;" />
                  </td>
                  <td style="width: 80px; padding: 4px; border: 1px solid #ebeef5;">
                    <el-input v-model="property.precisions" type="number" placeholder="精度" size="small" style="width: 100%;" />
                  </td>
                  <td style="width: 100px; padding: 4px; border: 1px solid #ebeef5;">
                    <el-select v-model="property.accessMode" placeholder="读取方式" size="small" style="width: 100%;">
                      <el-option label="读" value="read" />
                      <el-option label="写" value="write" />
                      <el-option label="上报" value="report" />
                    </el-select>
                  </td>
                  <td style="width: 120px; padding: 4px; border: 1px solid #ebeef5;">
                    <el-input v-model="property.value" placeholder="属性值" size="small" style="width: 100%;" />
                  </td>
                    <td style="width: 120px; padding: 4px; border: 1px solid #ebeef5;">
                    <el-input v-model="property.comment" placeholder="描述" size="small" style="width: 100%;" />
                  </td>
                  <td style="width: 80px; padding: 4px; border: 1px solid #ebeef5; text-align: center;">
                    <el-button type="danger" size="small" @click="removeProperty(index)" style="padding: 0; width: 60px; height: 28px;">删除</el-button>
                  </td>
                </tr>
                <!-- 空状态 -->
                <tr v-if="formData.properties.length === 0">
                  <td colspan="7" style="text-align: center; padding: 20px; border: 1px solid #ebeef5;">No Data</td>
                </tr>
              </tbody>
            </table>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 查看物属性对话框 -->
    <el-dialog 
      v-model="propertyDialogVisible" 
      title="产品物属性列表" 
      width="1200px"
      :close-on-click-modal="false"
      draggable
    >
      <el-table 
        :data="propertyList" 
        style="width: 100%;"
        border
        v-loading="propertyLoading"
        empty-text="暂无数据"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="propertyName" label="属性名称" width="150" align="center" />
        <el-table-column prop="dataType" label="数据类型" width="100" align="center" />
        <el-table-column prop="dataRange" label="数据范围" width="150" align="center" />
        <el-table-column prop="precisions" label="精度" width="80" align="center" />
        <el-table-column prop="accessMode" label="访问模式" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getAccessModeType(scope.row.accessMode)" size="small">
              {{ getAccessModeText(scope.row.accessMode) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="value" label="当前值" width="100" align="center" />
        <el-table-column prop="createdTime" label="创建时间" width="180" align="center" />
        <el-table-column prop="createdBy" label="创建人" width="100" align="center" />
        <el-table-column prop="value" label="当前值" width="100" align="center" />
        <el-table-column prop="createdTime" label="创建时间" width="180" align="center" />
        <el-table-column prop="createdBy" label="创建人" width="100" align="center" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessageBox, ElDialog, ElTable, ElTableColumn, ElTag, ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElButton, ElIcon } from 'element-plus'
import notificationService from '../utils/notificationService.js'
import { Search } from '@element-plus/icons-vue'
import { productAPI } from '../api/product.js'
import { productTypeAPI } from '../api/productType.js'
import axios from '../api/axios.js'

const products = ref([])
const productTypes = ref([])
const searchQuery = ref('')
const selectedProductTypeId = ref('')
const dialogVisible = ref(false)
const dialogTitle = ref('新增产品')
const loading = ref(false)
const typesLoading = ref(false)
const formRef = ref() // 添加formRef引用
const showPasswords = ref({}) // 用于控制每个产品的密码可见性
// 新增物属性对话框状态
const propertyDialogVisible = ref(false)
const propertyList = ref([])
const propertyLoading = ref(false)
const currentProductId = ref(null)

// 新增分页相关状态
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pages: 0
})

// 切换密码可见性函数
const togglePasswordVisibility = (productId) => {
  showPasswords.value[productId] = !showPasswords.value[productId]
}

// 更新表单数据模型
const formData = reactive({
  id: null,
  code: '',
  name: '',
  productTypeId: '',
  comment: '',
  accessMethod: 'mqtt',
  authMethod: '',
  status: '0',
  authPassword: '',
  properties: []
})

// 添加查看物属性方法
const viewProductProperties = async (productId) => {
  currentProductId.value = productId
  propertyDialogVisible.value = true
  await fetchProductProperties(productId)
}

// 获取产品属性列表
const fetchProductProperties = async (productId) => {
  propertyLoading.value = true
  try {
    const response = await axios.get('/productProperty/list', {
      params: {
        pageSize: 10,
        currentPage: 1,
        productId: productId
      }
    })
    
    // 支持20000-20003成功状态码范围
      if (response.code >= 20000 && response.code <= 20003) {
      propertyList.value = response.data?.records || []
    } else {
      ElMessage.error(response.message || '获取物属性列表失败')
      // 提供模拟数据
      propertyList.value = [
        {
          id: 1,
          productId: productId,
          deviceId: 0,
          property: "温度",
          propertyName: "温度",
          dataType: "double",
          dataRange: "-40~85",
          precisions: 1,
          accessMode: "read",
          value: "25.6",
          createdTime: "2025-09-27 16:34:30",
          createdBy: "Wb",
          deleted: "正常"
        },
        {
          id: 2,
          productId: productId,
          deviceId: 0,
          property: "湿度",
          propertyName: "湿度",
          dataType: "int",
          dataRange: "0~100",
          precisions: 0,
          accessMode: "report",
          value: "60",
          createdTime: "2025-09-27 16:34:30",
          createdBy: "Wb",
          deleted: "正常"
        },
        {
          id: 3,
          productId: productId,
          deviceId: 0,
          property: "风速",
          propertyName: "风速",
          dataType: "double",
          dataRange: "0~50",
          precisions: 2,
          accessMode: "write",
          value: "3.25",
          createdTime: "2025-09-27 16:34:30",
          createdBy: "Wb",
          deleted: "正常"
        }
      ]
    }
  } catch (error) {
    // 使用后端返回的错误信息或默认错误提示
    const errorMessage = error.response?.data?.message || error.message || '获取物属性列表失败'
    notificationService.error(errorMessage)
    console.error('获取物属性列表失败:', error)
    // 提供模拟数据
    propertyList.value = [
      {
        id: 1,
        productId: productId,
        deviceId: 0,
        property: "温度",
        propertyName: "温度",
        dataType: "double",
        dataRange: "-40~85",
        precisions: 1,
        accessMode: "read",
        value: "25.6",
        createdTime: "2025-09-27 16:34:30",
        createdBy: "Wb",
        deleted: "正常"
      },
      {
        id: 2,
        productId: productId,
        deviceId: 0,
        property: "湿度",
        propertyName: "湿度",
        dataType: "int",
        dataRange: "0~100",
        precisions: 0,
        accessMode: "report",
        value: "60",
        createdTime: "2025-09-27 16:34:30",
        createdBy: "Wb",
        deleted: "正常"
      },
      {
        id: 3,
        productId: productId,
        deviceId: 0,
        property: "风速",
        propertyName: "风速",
        dataType: "double",
        dataRange: "0~50",
        precisions: 2,
        accessMode: "write",
        value: "3.25",
        createdTime: "2025-09-27 16:34:30",
        createdBy: "Wb",
        deleted: "正常"
      }
    ]
  } finally {
    propertyLoading.value = false
  }
}

// 获取访问模式的标签类型
const getAccessModeType = (mode) => {
  switch (mode) {
    case 'read':
      return 'info'
    case 'write':
      return 'warning'
    case 'report':
      return 'success'
    default:
      return 'default'
  }
}

// 获取访问模式的中文文本
const getAccessModeText = (mode) => {
  switch (mode) {
    case 'read':
      return '可读'
    case 'write':
      return '可写'
    case 'report':
      return '上报'
    default:
      return mode
  }
}

// 提交表单
const submitForm = async () => {
  // 验证表单
  await formRef.value.validate()
  
  // 构建提交数据
  const submitData = {
    ...formData,
    // 将产品类型ID映射回typeId
    typeId: formData.productTypeId
  }
  
  try {
    let response
    if (formData.id) {
      // 编辑模式 - 使用code而不是id
      response = await productAPI.updateProduct(formData.code, submitData)
    } else {
      // 新增模式
      response = await productAPI.createProduct(submitData)
    }
    
    // 支持20000-20003成功状态码范围
      if (response.code >= 20000 && response.code <= 20003) {
      notificationService.success(formData.id ? '产品更新成功' : '产品创建成功')
      dialogVisible.value = false
      fetchProducts() // 重新获取产品列表
    } else {
      notificationService.error(response.message || '操作失败')
    }
  } catch (error) {
    // 使用后端返回的错误信息或默认错误提示
    const errorMessage = error.response?.data?.message || error.message || (formData.id ? '产品更新失败' : '产品创建失败')
    notificationService.error(errorMessage)
    console.error('提交表单失败:', error)
  }
}

// 显示新增产品对话框
const showAddDialog = () => {
  dialogTitle.value = '新增产品'
  // 初始化表单数据
  Object.assign(formData, {
    id: null,
    name: '',
    code: '',
    productTypeId: '',
    accessMethod: 'mqtt',
    authMethod: '',
    status: '0', // 使用默认启用状态的数字码值
    comment: '',
    authPassword: '',
    properties: []
  })
  dialogVisible.value = true
}

// 分页大小变更处理函数
const handleSizeChange = (newSize) => {
  pagination.pageSize = newSize
  pagination.currentPage = 1 // 重置为第一页
  fetchProducts()
}

// 当前页码变更处理函数
const handleCurrentChange = (newPage) => {
  pagination.currentPage = newPage
  fetchProducts()
}

// 搜索处理函数 - 直接调用fetchProducts
const handleSearch = () => {
  pagination.currentPage = 1 // 搜索时重置为第一页
  fetchProducts()
}

// 监听搜索输入框变化，添加延迟搜索
let searchTimer = null
const debounceSearch = () => {
  if (searchTimer) {
    clearTimeout(searchTimer)
  }
  searchTimer = setTimeout(() => {
    handleSearch()
  }, 300)
}

// 获取产品列表
const fetchProducts = async () => {
  loading.value = true
  try {
    // 构建请求参数，包括分页和搜索，注意将typeId改为type
    const params = {
      pageSize: pagination.pageSize,
      currentPage: pagination.currentPage,
      searchKey: searchQuery.value || undefined,
      type: selectedProductTypeId.value || undefined // 改为type参数
    }
    
    const response = await productAPI.getProducts(params)
    
    // 支持20000-20003成功状态码范围
      if (response.code >= 20000 && response.code <= 20003) {
      // 更新分页信息
      pagination.total = response.data?.total || 0
      pagination.pages = response.data?.pages || 0
      
      // 处理返回数据，转换字段名
      products.value = response.data?.records?.map(item => ({
        id: item.id,
        name: item.name,
        code: item.code,
        productTypeId: item.typeId,
        productTypeName: item.typeName,
        accessMethod: item.accessMethod,
        authMethod: item.authMethod,
        status: item.status, // 直接使用接口返回的字符串状态值
        description: item.description || '',
        authPassword: item.authPassword,
        updatedTime: item.updatedTime,
        updatedBy: item.updatedBy,
        createdTime: item.createdTime,
        createdBy: item.createdBy,
        deleted: item.deleted, // 直接使用接口返回的字符串删除状态
        properties: item.propertyVoList || []
      })) || []
    } else {
      notificationService.error(response.message || '操作失败')
    }
  } catch (error) {
      // 使用后端返回的错误信息或默认错误提示
      const errorMessage = error.response?.data?.message || error.message || '获取产品列表失败'
      notificationService.error(errorMessage)
      console.error('获取产品列表失败:', error)
      // 在API不可用时，提供模拟数据
    pagination.total = 3
    pagination.pages = 1
    products.value = [
      {
        id: 1,
        code: "po000001",
        name: "车削设备",
        typeId: 1,
        typeName: "机床类设备",
        productTypeId: 1,
        productTypeName: "机床类设备",
        accessMethod: "MQTT",
        authMethod: "DEVICEPASSWORD",
        status: "产品启用（可关联设备）",
        description: "",
        authPassword: "Passw0rd",
        updatedTime: "2025-08-28 14:08:20",
        updatedBy: "Wb",
        createdTime: "2025-04-27 16:34:30",
        createdBy: "Wb",
        deleted: "正常"
      },
      {
        id: 2,
        code: "po000002",
        name: "起重机",
        typeId: 4,
        typeName: "起重类设备",
        productTypeId: 4,
        productTypeName: "起重类设备",
        accessMethod: "MQTT",
        authMethod: "DEVICEPASSWORD",
        status: "产品启用（可关联设备）",
        description: "",
        authPassword: "Passw0rd",
        updatedTime: "2025-09-28 10:29:19",
        updatedBy: "Wb",
        createdTime: "2025-08-28 09:48:04",
        createdBy: "Wb",
        deleted: "正常"
      },
      {
        id: 3,
        code: "po000003",
        name: "油漆",
        typeId: 2,
        typeName: "涂装类设备",
        productTypeId: 2,
        productTypeName: "涂装类设备",
        accessMethod: "MQTT",
        authMethod: "DEVICEPASSWORD",
        status: "产品启用（可关联设备）",
        description: "",
        authPassword: "Passw0rd",
        updatedTime: "2025-08-28 15:37:22",
        updatedBy: "Wb",
        createdTime: "2025-08-28 15:23:16",
        createdBy: "Wb",
        deleted: "正常"
      }
    ]
  } finally {
    loading.value = false
  }
}

// 获取产品类型列表
const fetchProductTypes = async () => {
  typesLoading.value = true
  try {
    // 使用新接口获取产品类型列表
    const response = await productTypeAPI.getProductTypeList()
    // 从API响应中正确提取数据（根据用户提供的返回参数结构）
    productTypes.value = response.data?.typeList || []
  } catch (error) {
    notificationService.error('操作失败')
    console.error('获取产品类型列表失败:', error)
    // 在API不可用时，提供模拟数据，格式与真实API返回一致
    productTypes.value = [
      {
        id: 1,
        enName: 'machine tool',
        cnName: '机床类设备',
        comment: '机床类设备类型',
        updatedTime: null,
        updatedBy: null,
        createdTime: '2025-01-25 10:30:17',
        createdBy: 'system',
        deleted: '正常'
      },
      {
        id: 2,
        enName: 'coating equipment',
        cnName: '涂装类设备',
        comment: '涂装类设备类型',
        updatedTime: null,
        updatedBy: null,
        createdTime: '2025-01-25 10:30:17',
        createdBy: 'system',
        deleted: '正常'
      },
      {
        id: 3,
        enName: 'heat treatment equipment',
        cnName: '热处理类设备',
        comment: '热处理类设备类型',
        updatedTime: null,
        updatedBy: null,
        createdTime: '2025-01-25 10:30:17',
        createdBy: 'system',
        deleted: '正常'
      }
    ]
  } finally {
    typesLoading.value = false
  }
}



// 编辑产品
const editProduct = async (product) => {
  // 将选中的产品数据复制到表单中
  Object.assign(formData, {
    id: product.id,
    name: product.name,
    code: product.code,
    productTypeId: product.productTypeId,
    accessMethod: product.accessMethod,
    authMethod: product.authMethod,
    // 状态值根据产品状态文本转换为数字码
    status: product.status.includes('启用') ? '0' : '1',
    comment: product.description || '',
    authPassword: product.authPassword || '',
    properties: [] // 初始化空数组，稍后会填充物模型数据
  })
  
  try {
    // 调用接口获取产品的物模型数据
    const response = await axios.get('/productProperty/list', {
      params: {
        pageSize: 10,
        currentPage: 1,
        productId: product.id
      }
    })
    
    // 支持20000-20003成功状态码范围
      if ((response.code >= 20000 && response.code <= 20003) && response.data && response.data.records) {
      // 处理获取到的物模型数据，排除不需要的字段
      formData.properties = response.data.records.map(prop => {
        // 创建新对象，只包含需要的字段
        return {
          id: prop.id,
          productId: prop.productId,
          deviceId: prop.deviceId,
          property: prop.property || '',
          propertyName: prop.propertyName || '',
          dataType: prop.dataType || 'integer',
          dataRange: prop.dataRange || '',
          precisions: prop.precisions || 0,
          accessMode: prop.accessMode || 'read',
          value: prop.value || '',
          comment: prop.comment || '',
          deleted: prop.deleted.includes("正常")? '0':'1'
        }
      })
    }
  } catch (error) {
      notificationService.error('操作失败')
      console.error('获取物模型数据失败:', error)
    // 提供模拟数据作为备选
    formData.properties = [
      {
        property: '温度',
        propertyName: '温度',
        dataType: 'double',
        dataRange: '-40~85',
        precisions: 1,
        accessMode: 'read',
        value: '25.6'
      },
      {
        property: '湿度',
        propertyName: '湿度',
        dataType: 'int',
        dataRange: '0~100',
        precisions: 0,
        accessMode: 'report',
        value: '60'
      },
      {
        property: '风速',
        propertyName: '风速',
        dataType: 'double',
        dataRange: '0~50',
        precisions: 2,
        accessMode: 'write',
        value: '3.25'
      }
    ]
  }
  
  // 打开编辑对话框
  dialogVisible.value = true
  dialogTitle.value = '编辑产品'
}

// 删除产品
const deleteProduct = async (id) => {
  // 查找对应id的产品code
  const product = products.value.find(p => p.id === id)
  if (!product) {
    notificationService.error('操作失败')
    return
  }
  
  ElMessageBox.confirm('确定要删除这个产品吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    loading.value = true
    try {
      // 使用产品code删除
      await productAPI.deleteProduct(product.code)
      notificationService.success('删除成功')
      // 重新获取列表
      await fetchProducts()
    } catch (error) {
      notificationService.error('操作失败')
      console.error('删除失败:', error)
    } finally {
      loading.value = false
    }
  }).catch(() => {
    notificationService.info('已取消删除')
  })
}

// 切换产品状态
const toggleStatus = async (product) => {
  try {
    // 根据当前状态切换到相反状态
    const isCurrentlyEnabled = product.status.includes('启用');
    const newStatusText = isCurrentlyEnabled 
      ? '产品禁用（不可关联设备）' 
      : '产品启用（可关联设备）';
    const newStatusValue = isCurrentlyEnabled ? 0 : 1; // 1启用，0禁用
    
    // 临时更新状态以提供即时反馈
    const originalStatus = product.status;
    product.status = newStatusText;
    
    // 使用产品code而不是id，按照API要求的路径格式
    const response = await axios.put(`/product/${product.code}/updateStatus?status=${newStatusValue}`);
    
    // 支持20000-20003成功状态码范围
      if (response.code >= 20000 && response.code <= 20003) {
      notificationService.success('状态更新成功');
    } else {
      // 如果更新失败，恢复原始状态
      product.status = originalStatus;
      notificationService.error(response.message || '操作失败');
    }
  } catch (error) {
    // 如果发生错误，恢复原始状态
    fetchProducts(); // 重新获取列表以恢复正确状态
    notificationService.error('操作失败');
    console.error('状态更新失败:', error);
  }
}

// 添加物模型属性
const addProperty = () => {
  formData.properties.push({
    property: '',
    propertyName: '',
    dataType: 'integer',
    dataRange: '',
    precisions: 0,
    accessMode: 'read',
    value: '',
    comment: ''
  })
}

// 删除物模型属性
const removeProperty = (index) => {
  formData.properties.splice(index, 1)
}

// 组件挂载时获取数据
onMounted(() => {
  fetchProducts()
  fetchProductTypes()
})
</script>
<style scoped>
.product-management {
  padding: 0;
  margin: 0;
  min-height: calc(100vh - 130px);
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  position: relative;
  overflow: hidden;
}

/* 装饰性背景元素 */
.background-decorations {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
}

.bg-circle {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.15);
  animation: float 8s ease-in-out infinite;
}

.bg-circle-1 {
  width: 300px;
  height: 300px;
  top: -100px;
  right: -100px;
  animation-delay: 0s;
}

.bg-circle-2 {
  width: 200px;
  height: 200px;
  bottom: -50px;
  left: -50px;
  animation-delay: 2s;
}

.bg-circle-3 {
  width: 150px;
  height: 150px;
  top: 50%;
  left: 10%;
  animation-delay: 4s;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0) rotate(0deg);
  }
  50% {
    transform: translateY(-20px) rotate(5deg);
  }
}

/* 管理内容区域 - 移除卡片样式，直接展示 */
.management-content {
  position: relative;
  z-index: 1;
  width: 100%;
  box-sizing: border-box;
  background: white;
  min-height: calc(100vh - 130px);
  display: flex;
  flex-direction: column;
}

/* 按钮样式 */
.primary-button {
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
  transition: all 0.3s ease;
}

.primary-button:hover {
  background: linear-gradient(90deg, #5a67d8 0%, #6b46c1 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

/* 搜索区域样式 */
.search-container {
  display: flex;
  gap: 15px;
  padding: 20px 24px;
  align-items: center;
  flex-wrap: wrap;
  width: 100%;
  box-sizing: border-box;
  border-bottom: 1px solid #ebeef5;
  justify-content: space-between;
}

.search-input {
  width: 280px;
  max-width: 100%;
}

.search-select {
  width: 180px;
  max-width: 100%;
}

/* 搜索框样式 */
:deep(.el-input__wrapper) {
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.8);
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.2);
}

/* 下拉选择器样式 */
:deep(.el-select) {
  border-radius: 8px;
}

:deep(.el-select__wrapper) {
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.8);
}

:deep(.el-select__wrapper:hover) {
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.2);
}

/* 表格样式 - 添加完整边框并调整内边距 */
:deep(.el-table) {
  --el-table-header-bg-color: rgba(102, 126, 234, 0.1);
  --el-table-header-text-color: #667eea;
  width: calc(100% - 40px);
  flex: 1;
  margin: 0 20px;
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 0;
  --el-table-border-color: #ebeef5;
  --el-table-row-hover-bg-color: rgba(102, 126, 234, 0.05);
}

/* 确保表格头部颜色完全填充 */
:deep(.el-table__header-wrapper) {
  width: 100% !important;
  border-radius: 0;
  border-right: 1px solid #ebeef5;
}

:deep(.el-table__header) {
  width: 100% !important;
  border-radius: 0;
}

/* 表格主体区域边框 */
:deep(.el-table__body-wrapper) {
  border-right: 1px solid #ebeef5;
}

/* 表格单元格边框 */
:deep(.el-table__row td.el-table__cell) {
  border-right: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}

/* 表格头部单元格边框 */
:deep(.el-table__header th.el-table__cell) {
  background-color: rgba(102, 126, 234, 0.1) !important;
  padding: 12px 0;
  text-align: center;
  border-right: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}

/* 覆盖Element UI默认样式，确保右侧固定列也有边框 */
:deep(.el-table__fixed-right) {
  box-shadow: none !important;
  border-left: 1px solid #ebeef5;
}

/* 确保最后一行也有底边框 */
:deep(.el-table__row:last-child td.el-table__cell) {
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-table__row) {
  transition: background-color 0.2s ease;
}

:deep(.el-table__row:hover) {
  background-color: rgba(102, 126, 234, 0.05);
}

/* 分页样式 */
.pagination-container {
  padding: 20px 24px 20px calc(24px + 20px);
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

/* 对话框样式优化 */
.el-dialog {
  max-width: 90vw;
  margin: 20px auto;
  width: auto !important;
}

:deep(.el-dialog__header) {
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  border-radius: 8px 8px 0 0;
}

:deep(.el-dialog__title) {
  color: white;
  font-weight: bold;
}

:deep(.el-dialog__close) {
  color: white;
}

:deep(.el-dialog__body) {
  padding: 24px;
  background: white;
  max-height: 60vh;
  overflow-y: auto;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px;
  background: #f9f9f9;
  border-radius: 0 0 8px 8px;
}

/* 表单样式 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #303133;
}

/* 标签样式 */
:deep(.el-tag) {
  border-radius: 4px;
  padding: 0 8px;
  height: 24px;
  line-height: 24px;
}
</style>